import { getCartList, updateCartNum, deleteGoods } from '@/api/cart'
import { Toast } from 'vant'
export default {
// 开启命名空间
  namespaced: true,
  state: {
    cartList: []
  },
  mutations: {
    // 进行修改cartList
    setCartList (state, list) {
      state.cartList = list
    },
    // 进行修改商品的选中状态
    changeGoodsChecked (state, goods) {
      state.cartList.forEach(element => {
        if (element.goods_id === goods.goods_id) {
          element.isChecked = goods.isChecked
        }
      })
    },
    // 进行全选
    changeAllChecked (state, isAllChecked) {
      state.cartList.forEach(element => {
        element.isChecked = isAllChecked
      })
    },
    // 进行更新商品购物车数量
    changeGoodsNum (state, { goodsId, goodsNum }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  actions: {
    // 获取商品列表
    async getCartAction (context) {
      const { data: { data: { list } } } = await getCartList()
      // 为每一个商品进行添加一个属性，用于判断是否被选中
      list.forEach(element => {
        element.isChecked = true
      })
      // 进行提交修改仓库列表的操作
      context.commit('setCartList', list)
    },
    // 进行更新商品购物车数量
    async updateCartNumAction (context, goods) {
      console.log(goods)
      await updateCartNum(goods.goodsId, goods.goodsNum, goods.goodsSkuId)
      context.commit('changeGoodsNum', goods)
    },
    // 删除购物车商品
    async deleteCartAction (context, cartIds) {
      console.log(cartIds)
      const res = await deleteGoods(cartIds)
      console.log(res)
      Toast('删除成功')
      // 进行重新获取商品列表
      context.dispatch('getCartAction')
    }
  },
  getters: {
    // 获取商品的总数
    getCartListTotal (state) {
      return state.cartList.reduce((sum, item, index) => sum + item.goods_num, 0)
    },
    // 选中的商品项目
    getCheckedGoods (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 选中的总数
    getCheckedGoodsTotal (state) {
      return state.cartList.filter(item => item.isChecked).reduce((sum, item, index) => sum + item.goods_num, 0)
    },
    // 选中的总价
    getCheckedGoodsTotalPrice (state) {
      return state.cartList.filter(item => item.isChecked).reduce((sum, item, index) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2)
    },
    // 判断是否进行了全选
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
